package cn.gok.webSocket;

import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * @Author: chen fan
 * @Date: 2022/3/17 20:11
 * @Description:
 */
@ServerEndpoint("/webSocketServer")
public class WebSocketServer {

    /**
     * 存放着和浏览器交互的session对象
     */
    private static List<Session> sessions = new ArrayList<>();

    @OnOpen
    public void onOpen(Session session){
        sessions.add(session);
    }

    @OnMessage
    public void onMessage(String message, Session session){
        for (Session browserSession : sessions) {
            try {
                browserSession.getBasicRemote().sendText(message);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    @OnClose
    public void onClose(Session session){
        sessions.remove(session);
    }
}
